package com.mianyang.zhangsan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mianyang.zhangsan.common.constant.SecConstant;
import com.mianyang.zhangsan.common.util.RandUtils;
import com.mianyang.zhangsan.common.util.StringUtils;
import com.mianyang.zhangsan.exception.SecServiceException;
import com.mianyang.zhangsan.model.dto.SecProblemAnswerDto;
import com.mianyang.zhangsan.model.entity.SecAnswer;
import com.mianyang.zhangsan.model.entity.SecBank;
import com.mianyang.zhangsan.model.entity.SecPaperBank;
import com.mianyang.zhangsan.model.entity.SecProblem;
import com.mianyang.zhangsan.model.entity.SecProblemGroup;
import com.mianyang.zhangsan.service.SecAnswerService;
import com.mianyang.zhangsan.service.SecProblemService;
import com.mianyang.zhangsan.mapper.SecProblemMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.function.Function;

/**
* @author jiangjr
*/
@Service
public class SecProblemServiceImpl extends ServiceImpl<SecProblemMapper, SecProblem>
    implements SecProblemService{
    @Autowired
    private SecAnswerService answerService;

    @Override
    public List<SecProblem> selectProblemByRandom(Long bankId, Integer num, Integer type) {
        Assert.notNull(bankId, "未指定题库");
        Assert.notNull(type, "未指定题型");
        // 查询一共多少到题
        QueryWrapper<SecProblem> wrapper = new QueryWrapper<>();
        wrapper.eq("bank_id", bankId);
        wrapper.eq("problem_type", type);
        long count = count(wrapper);
        if (count <= num) {
            return list(wrapper);
        }
        long maxId = count - num;
        // 保证一定能取到足够的数量
        Integer randNum = RandUtils.range(1, Integer.parseInt("" + maxId));
        return baseMapper.selectByRandom(randNum, num);
    }

    @Override
    public Page<SecProblem> selectProOfBank(SecProblem problem , Integer current, Integer pageSize) {
        QueryWrapper<SecProblem> wrapper = new QueryWrapper<>();
        wrapper.select("problem_id", "problem_desc", "problem_type", "problem_right", "analysis", "bank_id", "bank_name");
        if (problem.getBankId() != null) {
            wrapper.eq("bank_id", problem.getBankId());
        }
        if (StringUtils.isNotEmpty(problem.getProblemDesc())) {
            wrapper.like("problem_desc", problem.getProblemDesc());
        }
        if (problem.getProblemType() != null) {
            wrapper.eq("problem_type", problem.getProblemType());
        }
        return page(new Page<>(current, pageSize), wrapper);
    }

    @Override
    public List<SecProblemGroup> selectDataGroupBy(String column) {
        return getBaseMapper().selectProblemGroupBy(column);
    }

    @Override
    public void updateProblemAndAnswer(SecProblemAnswerDto problemInfo) {
        // 保存问题信息
        SecProblem problem = problemInfo.getProblem();
        Long problemId = problem.getProblemId();
        if (problemId == null) {
            throw new SecServiceException("未找到相关试题");
        }
        List<SecAnswer> baseAnswers = answerService.selectAnswerByProblemId(problemId);
        List<SecAnswer> answers = problemInfo.getAnswers();
        List<Long> deleteAnswerIds = new ArrayList<>();
        baseAnswers.forEach(answer -> {
            Optional<SecAnswer> first = answers.stream().filter(item -> item.getAnswerId() != null && answer.getAnswerId().equals(item.getAnswerId()))
                    .findFirst();
            if (!first.isPresent()) {
                deleteAnswerIds.add(answer.getAnswerId());
            }
        });
        // 删除答案
        answerService.removeBatchByIds(deleteAnswerIds);
        // 保存答案
        Long answerId = answerService.updateAndGetRightId(answers, problemId);
        // 更新问题正确答案编号
        problem.setProblemRight(answerId);
        updateById(problem);

    }

    @Override
    public void deleteProblemAndAnswer(Long problemId) {
        // 删除问题信息
        removeById(problemId);
        // 删除问题相关的答案
        answerService.removeByProblemId(problemId);
    }
}




